﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using DataBaseLibrary.DBObjectsFB;
using DataBaseLibrary.DBInterfaces;


namespace DocMreoLiteVersion.Reports.SaleContractReport
{



    public class BoolToSizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return 0;
            bool val = (bool) value;
            if (val)
                return GridLength.Auto;
            
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((GridLength) value == GridLength.Auto)
                return true;
            else
                return false;
        }
    }


    /// <summary>
    /// Interaction logic for FormSalesContract.xaml
    /// </summary>
    public partial class FormSalesContract : UserControl
    {


        /// <summary>
        /// Событие закрытия формы
        /// </summary>
        delegate void CloseFormSalesEventHandler(object sender, RoutedEventArgs args);
        public static readonly RoutedEvent CloseFormSalesContractEvent = EventManager.RegisterRoutedEvent("CloseFormSalesContract", RoutingStrategy.Bubble, typeof(CloseFormSalesEventHandler), typeof(FormSalesContract));

        public event RoutedEventHandler CloseFormSalesContract
        {
            add { AddHandler(CloseFormSalesContractEvent, value); }
            remove { RemoveHandler(CloseFormSalesContractEvent, value); }
        }

        public static DependencyProperty idRecordProperty = DependencyProperty.Register("ID_RECORD", typeof(String), typeof(FormSalesContract));
        
        //ID полученной записи!
        public String ID_RECORD
        {
            set { SetValue(idRecordProperty, value); }
            get { return (String)GetValue(idRecordProperty); }
        }

        /// <summary>
        /// Объект договора купли-продажи
        /// </summary>
        private IDBObject mSalesContract = null;

        /// <summary>
        /// Провайдер базы данных
        /// </summary>
        private IDBProvider db_provider = null;



        private static DependencyProperty IsRepresentativeProperty = DependencyProperty.Register("IsRepresentative",
            typeof (bool), typeof (FormSalesContract), new PropertyMetadata(false));

        /// <summary>
        /// Признак отображения полей ввода для представителей
        /// </summary>
        public bool IsRepresentative
        {
            get { return (bool)GetValue(IsRepresentativeProperty); }
            set
            {
                SetValue(IsRepresentativeProperty, value);
            }
        }



        /// <summary>
        /// Функция проверяет наличие представителей. Если представители
        /// имеются, то формирует признак IsRepresentative в Visible и возвр. true
        /// иначе Hidden и возвр false
        /// </summary>
        /// <returns></returns>
        private bool CheckRepresentative()
        {
            if ((mSalesContract as SalesContract).RepresentativeBuyer.OIndividual.LastName != String.Empty ||
                (mSalesContract as SalesContract).RepresentativeSaler.OIndividual.LastName != String.Empty)
            {
                IsRepresentative = true;
                return true;
            }
            IsRepresentative = false;
            return false;
        }


        /// <summary>
        /// Конструктор
        /// </summary>
        public FormSalesContract()
        {
            IsRepresentative = false;
            mSalesContract = new SalesContract();
            InitializeComponent();

            DataContext = mSalesContract;
            
        }

        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="m_provider">Провайдер БД</param>
        /// <param name="idRecord">ID договора</param>
        public FormSalesContract(IDBProvider m_provider, String idRecord = "")
            : this()
        {
            db_provider = m_provider;

            if (db_provider == null)
            {
                MessageBox.Show("Нет провайдера БД");
                return;
            }
            
            mSalesContract = new SalesContract();
            LoadSalesContract(idRecord);


            SalerGuiControl.Provider = m_provider;
            BuyerGuiControl.Provider = m_provider;

            SalerGuiControl.IndividualObject = (mSalesContract as SalesContract).Saler.m_Individual;
            BuyerGuiControl.IndividualObject = (mSalesContract as SalesContract).Buyer.m_Individual;
            RepresentativeSalerGuiControl.IndividualObject = (mSalesContract as SalesContract).RepresentativeSaler.OIndividual;
            RepresentativeBuyerGuiControl.IndividualObject =
                (mSalesContract as SalesContract).RepresentativeBuyer.OIndividual;
            TransportControl.VechicleObject = (mSalesContract as SalesContract).Vehicle;
            ProxySalerControl.RepresentativeObject = (mSalesContract as SalesContract).RepresentativeSaler;
            ProxyBuyerControl.RepresentativeObject = (mSalesContract as SalesContract).RepresentativeBuyer;
            DataContext = mSalesContract;
            
        }

        /// <summary>
        /// Поиск и загрузка договора по ID
        /// </summary>
        /// <param name="idRecord">ID договора</param>
        private void LoadSalesContract(String idRecord)
        {
            if (idRecord == ID_RECORD)
            {
                MessageBox.Show(String.Format("Договор {0} уже загружен!", ID_RECORD));
                return;
            }

            if (idRecord == String.Empty)
                return;

            try
            {
                db_provider.Load(mSalesContract, idRecord);
                ID_RECORD = idRecord;
                CheckRepresentative();
            }
            catch(SystemException err)
            {                
                MessageBox.Show(err.Message, "Ошибка ввода", MessageBoxButton.OK, MessageBoxImage.Error);
                MessageBox.Show("Будет создан новый договор!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
                ID_RECORD = "";
                mSalesContract = new SalesContract();

                DataContext = mSalesContract;

            }
        }

        /// <summary>
        /// Сохранение договора в БД
        /// </summary>
        private void SaveUpdateSalesContract()
        {
            if (db_provider == null)
                return;

            try
            {
                
                //TODO: Костыль!!


                if (ID_RECORD == "" || ID_RECORD == null)
                {
                    ID_RECORD = db_provider.Save(mSalesContract) as String;
                    IDBLogic logic = new FDBLogic(db_provider);
                    logic.AddDocumentHistory(MainWindow.session.user, ID_RECORD, mSalesContract.ToString(), "Создание", DateTime.Now, 100.00);
                }
                else
                {
                    db_provider.Update(mSalesContract);
                    IDBLogic logic = new FDBLogic(db_provider);
                    logic.AddDocumentHistory(MainWindow.session.user, ID_RECORD, mSalesContract.ToString(), "Обновление", DateTime.Now, 100.00);
                }
            }
            catch (SystemException err)
            {
                MessageBox.Show(String.Format("Ошибка с сообщением: ", err.Message));
            }
        }


        /// <summary>
        /// Распечатать договор
        /// </summary>
        private void PrintContract()
        {
            DataReportBindingSalesContract mDataReportBindingSalesContract = new DataReportBindingSalesContract(mSalesContract as SalesContract);
            ReportViewverWindow r_window = new ReportViewverWindow("DocMreoLiteVersion.Reports.SaleContractReport.SaleContractReport.rdlc", "SaleContractDataSet", mDataReportBindingSalesContract);

            r_window.Owner = System.Windows.Application.Current.MainWindow;
            r_window.ShowDialog();
            r_window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            r_window.m_ReportViewver.Refresh();
        }

        /// <summary>
        /// Распечатать договор с представителями
        /// </summary>
        private void PrintContractWithRepresentative()
        {
            DataReportBindingRepresentativeSale mDataReportBindingSalesContract = new DataReportBindingRepresentativeSale(mSalesContract as SalesContract);
            ReportViewverWindow r_window =  new ReportViewverWindow("DocMreoLiteVersion.Reports.SaleContractReport.SaleContractReportRepresentative.rdlc", "SalesDataSetRepresentative", mDataReportBindingSalesContract);

            r_window.Owner = System.Windows.Application.Current.MainWindow;
            r_window.ShowDialog();
            r_window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            r_window.m_ReportViewver.Refresh();
        }



        /// <summary>
        /// Завершить рабботу
        /// </summary>
        private void CloseContractForm()
        {
            RoutedEventCreateDeclarationArgs args = new RoutedEventCreateDeclarationArgs(FormSalesContract.CloseFormSalesContractEvent);
            if (ID_RECORD != null & ID_RECORD != String.Empty)
                args.ObjectContract = mSalesContract;
            else
                args.ObjectContract = null;
            RaiseEvent(args);
        }



        // События от кнопок

        private void RecButton_Click_1(object sender, RoutedEventArgs e)
        {
            SaveUpdateSalesContract();
            if (!(mSalesContract as SalesContract).RepresentativeSaler.OIndividual.LastName.Equals(String.Empty) ||
                !(mSalesContract as SalesContract).RepresentativeBuyer.OIndividual.LastName.Equals(String.Empty))
                PrintContractWithRepresentative();
            else
                PrintContract();
            
        }


        /// <summary>
        /// Отобразить форму заполнения данных для представителей
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateRepresentative_OnClick(object sender, RoutedEventArgs e)
        {
            if (IsRepresentative == false)
                IsRepresentative = true;
            else
                IsRepresentative = false;
        }



        /// <summary>
        /// Завершить работу
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click_1(object sender, RoutedEventArgs e)
        {
            CloseContractForm();
        }

    }
}
